package Controllers;

import java.util.Observable;

import javax.sound.midi.ControllerEventListener;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;

import Lecteurs.Service;
import Serveur.ServeurServices;

public class ControllerClient extends Observable implements ControllerEventListener {
	
	private ServeurServices serveur;
	private Sequencer sequenceur;
	private Service svc;
	
	private String msg ;
	
	public ControllerClient(ServeurServices serveur) {
		this.serveur = serveur ;
		
		try {
			sequenceur = MidiSystem.getSequencer();  //Recuperation du sequenceur par default 
			sequenceur.open();
		} catch (MidiUnavailableException e) {
			System.out.println(e.getMessage());
		}
			sequenceur.addControllerEventListener(this,null);
	}
	
	public void play(){
		
			if (svc == null){
				
				msg="serviceNull";
				this.setChanged();
				this.notifyObservers();
			}
			else{
				svc.sequencer(sequenceur);
				svc.play(sequenceur);
			}
	}
	
	public void stop(){
		
		if (svc == null){
			
			msg="serviceNull";
			this.setChanged();
			this.notifyObservers();
		}
		else{
			svc.stop(sequenceur);
		}	
	}
	
	public void chargerService(Object serviceChoisi) {
		try {
			svc = serveur.getService(serviceChoisi);
		} catch(Exception ex) {
			ex.printStackTrace();
			svc = null ;
		}
	}

	@Override
	public void controlChange(ShortMessage event) {
		msg="";
		this.setChanged();
		this.notifyObservers();
	}
	
	public String getMsg() {
		return msg;
	}
}